/**
 alice functions
 **/
var Alice = function () {

    var addRegexForValidator = function () {
        if(jQuery.validator){
            jQuery.validator.addMethod("regex", function (value, element, params) {
                var exp = new RegExp(params);
                return exp.test(value);
            }, "输入格式有误");
        }
    };

    var addRoleSelForValidator = function () {
        if(jQuery.validator){
            jQuery.validator.addMethod("checkRoleSel", function (value, element, params) {
                var v = value.split(",");
                return v.length <= params;
            }, "输入格式有误");
        }
    };

    var showDefaultSuccessGrowl = function (text, time) {
        $.bootstrapGrowl(text, {
            ele: 'body', // which element to append to
            type: 'success', // (null, 'info', 'danger', 'success', 'warning')
            offset: {
                from: 'top', // 'top', or 'bottom'
                amount: 0
            },
            align: 'center', // ('left', 'right', or 'center')
            width: 'auto', // (integer, or 'auto')
            delay: parseInt(time), // Time while the message will be displayed. It's not equivalent to the *demo* timeOut!
            allow_dismiss: true, // If true then will display a cross to close the popup.
            stackup_spacing: 10 // spacing between consecutively stacked growls.
        });
    };

    var showDefaultWarningGrowl = function (text, time) {
        $.bootstrapGrowl(text, {
            ele: 'body',
            type: 'warning',
            offset: {
                from: 'top',
                amount: 0
            },
            align: 'center',
            width: 'auto',
            delay: parseInt(time),
            allow_dismiss: true,
            stackup_spacing: 10
        });
    };

    var showDefaultFailAlert = function (error, res) {
        resetFailAlert(error);
        if (res) {
            var me = res.msgerrors;
            for (var i = 0; i < me.length; i++) {
                error.append("<span>" + me[i] + "</span><br />");
            }
        } else {
            error.append("<span>" + error.attr("data-text") + "</span>");
        }
        error.show("fast");
        Metronic.scrollTo(error, -200);
    };
    var showDefaultFailAlertByText = function (error, text) {
        resetFailAlert(error);
        if (text) {
            error.append("<span>" + text + "</span>");
        } else {
            error.append("<span>" + error.attr("data-text") + "</span>");
        }
        error.show("fast");
        Metronic.scrollTo(error, -200);
    };
    var resetFailAlert = function (error) {
        error.children().each(function () {
            if (!$(this).is("button")) {
                $(this).remove();
            }
        });
    }

    var resetValidator = function (form) {
        $(".form-group", form).each(function () {
            $(this).removeClass("has-success has-error");
        });
        $(".input-icon", form).children('i').each(function () {
            $(this).removeClass("fa-check fa-warning");
        });
    };

    var regMaxLength = function (list) {
        for(var i = 0;i < list.length;i++){
            $('#' + list[i]).maxlength({
                limitReachedClass: "label label-danger",
                alwaysShow: true,
                placement: 'top'
            });
        }
    };

    var groupCheckable = function (obj, c) {
        obj.find(c).change(function () {
            var set = jQuery(this).attr("data-set");
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                if (checked) {
                    $(this).attr("checked", true);
                } else {
                    $(this).attr("checked", false);
                }
            });
            jQuery.uniform.update(set);
        });
    };

    var permissionCheckable = function (obj, c, p) {
        obj.find(c).change(function () {
            var isChecked = true;
            var isNotChecked = true;
            var ckTd = jQuery(this).closest(p);

            ckTd.find("input:checkbox").each(function () {
                if($(this).attr("checked") == "checked"){
                    isNotChecked = false;
                }else{
                    isChecked = false;
                }
            });
            if(isChecked || isNotChecked){
                ckTd.parent().find(".ckgTd input:checkbox").each(function () {
                    if(isChecked){
                        $(this).attr("checked", true);
                    }
                    if(isNotChecked){
                        $(this).attr("checked", false);
                    }
                    jQuery.uniform.update($(this));
                });
            }
        });
    };

    //FormFileUpload
    var formFileUpload = function (obj) {
        obj.fileupload({
            //disableImageResize: false,
            autoUpload: false,
            disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
            maxFileSize: 5000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
        });

        obj.fileupload(
            'option',
            'redirect',
            window.location.href.replace(
                /\/[^\/]*$/,
                '/cors/result.html?%s'
            )
        );

    };

    var userPhoto = function(id) {
        // Create variables (in this scope) to hold the API and image size
        var jcrop_api,
            boundx,
            boundy,
            // Grab some information about the preview pane
            $preview = $('#preview-pane'),
            $pcnt = $('#preview-pane .preview-container'),
            $pimg = $('#preview-pane .preview-container img'),

            xsize = $pcnt.width(),
            ysize = $pcnt.height();

        console.log('init',[xsize,ysize]);

        $('#'+id).Jcrop({
            onChange: updatePreview,
            onSelect: updatePreview,
            aspectRatio: xsize / ysize
        },function(){
            // Use the API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            // Store the API in the jcrop_api variable
            jcrop_api = this;
            // Move the preview into the jcrop container for css positioning
            $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c)
        {
            if (parseInt(c.w) > 0)
            {
                var rx = xsize / c.w;
                var ry = ysize / c.h;

                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        };
    };

    var logout = function (path) {
        var logout = $('#logOut');
        if(logout){
            logout.on('click', function(e) {
                bootbox.dialog({
                    message:logout.attr("data-text"),
                    title: "登出确认",
                    buttons: {
                        danger: {
                            label: "登出",
                            className: "red",
                            callback: function () {
                                window.location.href = path + "/sdm/logout";
                            }
                        },
                        main: {
                            label: "取消",
                            className: "default"
                        }
                    }
                });
            });
        }
    };

    var encryptRSA = function (m, e, text) {
        setMaxDigits(130);
        var key = new RSAKeyPair(e, "", m);
        return encryptedString(key, text);
    };

    return {

        init: function () {

            //增加正则表达式验证方法
            addRegexForValidator();

        },

        //登出
        logout: function (path) {
            logout(path);
        },

        //RSA加密
        encryptRSA: function (m, e, text) {
            return encryptRSA(m, e, text);
        },

        //用户头像控件
        userPhoto: function (id) {
            userPhoto(id);
        },

        //图片上传控件
        formFileUpload: function (obj) {
            formFileUpload(obj);
        },

        //
        permissionCheckable: function (obj, c, p) {
            permissionCheckable(obj, c, p);
        },

        //
        groupCheckable: function (obj, c) {
            groupCheckable(obj, c);
        },

        //
        regMaxLength: function (list) {
            regMaxLength(list);
        },

        //
        addRoleSelForValidator: function () {
            addRoleSelForValidator();
        },

        //
        showDefaultSuccessGrowl: function (text, time) {
            var t = 4000;
            if(time){
                t = time;
            }
            showDefaultSuccessGrowl(text, t);
        },

        //显示警告信息,默认4秒后消失
        showDefaultWarningGrowl: function (text, time) {
            var t = 4000;
            if(time){
                t = time;
            }
            showDefaultWarningGrowl(text, t);
        },

        //
        resetValidatorForm: function (form) {
            form.reset();
            resetValidator(form);
        },

        //
        resetValidator: function (form) {
            resetValidator(form);
        },

        //
        showDefaultFailAlert: function (errorObj, res) {
            showDefaultFailAlert(errorObj, res);
        },

        //
        showDefaultFailAlertByText: function (errorObj, text) {
            showDefaultFailAlertByText(errorObj, text);
        }

    };

}();